package com.cennavi.minemapdemo.activity.ue;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.activity.BaseActivty;
import com.cennavi.minemapdemo.util.BitmapUtil;
import com.cennavi.minemapdemo.util.Config;
import com.cennavi.minemapdemo.util.DensityUtil;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.camera.CameraUpdateFactory;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.MarkerLayer;
import com.minedata.minemap.overlay.MarkerLayerOptions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MapBaseControlActivty extends BaseActivty implements
        MineMap.OnMapClickListener,
        MineMap.OnMapLongClickListener,
        MineMap.OnCameraMoveListener,
        MineMap.OnCameraMoveStartedListener,
        MineMap.OnCameraIdleListener,
        MineMap.OnScaleChangedListener,
        MineMap.OnRotateListener,
        MineMap.OnShoveListener {

    //地图视图
    private MapView mapView;
    //地图操作类
    private MineMap mineMap;
    private LatLng lastLatLng, currentLatLng;
    private Context mContext;
    private boolean isRotate = false;
    private boolean isShove = false;

    MarkerLayerOptions.MarkerItem marker;
    MarkerLayer curPosition;

    private TextView btnScale;
    private TextView btnRotate;
    private TextView btnOverlook;

    private TextView txtCurPoint;
    private TextView txtMapState;

    private TextView btnSnapShot;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MinemapAccountManager.getInstance(this, Config.MAP_TOK, Config.OFFLINE_TOK, Config.MAP_ID);

        setContentView(R.layout.activity_ue_base_ctr);

        mContext = this;
        mapView = findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);

        initMap();
        initView();

    }

    private void initMap() {
        mapView.setApiBaseUrl(Config.API_BASE_URL);
        mapView.setApiUrl(Config.API_URL);
        mapView.setSpriteImageUrl(Config.SPRITE_GLYPHS_URL);
        mapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @SuppressLint("RtlHardcoded")
            @Override
            public void onMapReady(MineMap oMineMap) {
                mineMap = oMineMap;
                mineMap.getUiSettings().setZoomControlsEnabled(false);
                mineMap.getUiSettings().setRotateGesturesEnabled(true);// 是否可以旋转地图
                mineMap.getUiSettings().setTiltGesturesEnabled(true);
                mineMap.setStyleUrl(Config.BASE_URL + Config.MAP_ID, new MineMap.OnStyleLoadedListener() {
                    @Override
                    public void onStyleLoaded(String s) {
                        mineMap.setTrafficShow(false); //是否展示交通路况信息
                        addImageToMap();
                    }
                });
                //设置指南针是否显示，默认是显示
                mineMap.getUiSettings().setCompassEnabled(true);
                mineMap.getUiSettings().setCompassGravity(Gravity.LEFT);
//                mineMap.getUiSettings().setCompassImage(getResources().getDrawable(R.mipmap.icon_compass));
                mineMap.getUiSettings().setCompassMargins(DensityUtil.dip2px(mContext, 11), DensityUtil.dip2px(mContext, 80),
                        0, 0);
                mineMap.setCameraPosition(
                        new CameraPosition.Builder().target(new LatLng(Config.mapCentrelat, Config.mapCentrelon)).zoom(14)
                                .tilt(0)//设定倾斜角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .build());
                mineMap.setMaxZoomPreference(17);//设置最高展示级别，最高为17级别
                mineMap.setMinZoomPreference(3);//设置最低的展示级别

                mineMap.addOnMapClickListener(MapBaseControlActivty.this);
                mineMap.addOnCameraMoveStartedListener(MapBaseControlActivty.this);
                mineMap.addOnCameraMoveListener(MapBaseControlActivty.this);
                mineMap.addOnMapLongClickListener(MapBaseControlActivty.this);
                mineMap.addOnScaleChangedListener(MapBaseControlActivty.this);
                mineMap.addOnRotateListener(MapBaseControlActivty.this);
                mineMap.addOnShoveListener(MapBaseControlActivty.this);
            }
        });

    }

    //加载可能的图片资源
    private void addImageToMap() {
        Bitmap bitmap = BitmapUtil.drawableToBitmap(mContext, R.drawable.icon_marka);
        mineMap.addImage(R.drawable.icon_marka + "", bitmap);
    }

    private void initView() {

        txtCurPoint = findViewById(R.id.txt_cur_point);
        txtMapState = findViewById(R.id.txt_map_state);

        btnScale = findViewById(R.id.btn_scale);
        btnRotate = findViewById(R.id.btn_rotate);
        btnOverlook = findViewById(R.id.btn_overlook);

        btnSnapShot = findViewById(R.id.btn_snapshot);

        final ImageView zoomIn = findViewById(R.id.zoomin);
        final ImageView zoomOut = findViewById(R.id.zoomout);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (view.equals(btnScale)) {
                    perfomZoom();
                } else if (view.equals(btnRotate)) {
                    perfomRotate();
                } else if (view.equals(btnOverlook)) {
                    perfomOverlook();
                } else if (view.equals(btnSnapShot)) {
                    perfomSnapshot();
                } else if (view.equals(zoomIn)) {
                    zoomIn(view);
                } else if (view.equals(zoomOut)) {
                    zoomOut(view);
                }
            }
        };

        btnScale.setOnClickListener(clickListener);
        btnRotate.setOnClickListener(clickListener);
        btnOverlook.setOnClickListener(clickListener);
        btnSnapShot.setOnClickListener(clickListener);
        zoomIn.setOnClickListener(clickListener);
        zoomOut.setOnClickListener(clickListener);

    }

    public void zoomIn(View view) {
        if (mineMap != null) {
            mineMap.moveCamera(CameraUpdateFactory.zoomIn());
        }
    }

    public void zoomOut(View view) {
        if (mineMap != null) {
            mineMap.moveCamera(CameraUpdateFactory.zoomOut());
        }
    }


    /**
     * 处理 截屏事件
     */
    private void perfomSnapshot() {

        if (mineMap != null) {
            mineMap.snapshot(new MineMap.OnSnapshotReadyCallback() {
                @Override
                public void onSnapshotReady(Bitmap bitmap) {
                    @SuppressLint("SdCardPath")
                    String sdPath = Environment.getExternalStorageDirectory().getPath();
                    File file = new File(sdPath, "test.png");
                    if (file.exists()) {
                        file.delete();
                        try {
                            file.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    FileOutputStream out;
                    try {
                        out = new FileOutputStream(file);
                        if (bitmap.compress(
                                Bitmap.CompressFormat.PNG, 100, out)) {
                            out.flush();
                            out.close();
                        }

                        showToast("屏幕截图成功，图片存在: " + file.toString(), 1);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 处理缩放范围  [3, 17]   通过initmap初始化地图的时候确定
     */
    private void perfomZoom() {

        EditText txtScale = findViewById(R.id.txt_scale);
        try {
            double zoom = Double.parseDouble(txtScale.getText().toString());
            mineMap.setZoom(zoom);
        } catch (NumberFormatException e) {
            showToast("请输入正确缩放级别", 1);
        }
    }

    /**
     * 处理旋转  旋转角范围 [0, 360]
     */
    private void perfomRotate() {

        EditText txtRotate = findViewById(R.id.txt_rotate);
        try {
            double rotateAngle = Double.parseDouble(txtRotate.getText().toString());
            mineMap.setBearing(rotateAngle);
        } catch (NumberFormatException e) {
            showToast("请输入正确旋转角度", 1);
        }
    }

    /**
     * 处理俯视  倾角范围  [0, 60]
     */
    private void perfomOverlook() {

        EditText txtOverlook = findViewById(R.id.txt_overlook);
        try {
            double overlookAngle = Double.parseDouble(txtOverlook.getText().toString());
            mineMap.setTilt(overlookAngle);
        } catch (NumberFormatException e) {
            showToast("请输入正确倾斜角度", 1);
        }
    }

    /**
     * 处理地图状态文本
     */
    private void updateMapStateTxt(String clickType) {
        if (txtCurPoint != null) {
            currentLatLng = mineMap.getCameraPosition().getTarget();
            String txtPoint = String.format(clickType + "，当前经度：%.6f 当前纬度：%.6f", currentLatLng.getLongitude(), currentLatLng.getLatitude());
            txtCurPoint.setText(txtPoint);
            lastLatLng = currentLatLng;
        }

        if (txtMapState != null) {
            @SuppressLint("DefaultLocale")
            String temp = String.format("zoom=%.1f  rotate=%.1f  overlook=%.1f", mineMap.getCameraPosition().getZoom(), mineMap.getCameraPosition().getBearing(), mineMap.getCameraPosition().getTilt());
            txtMapState.setText(temp);
        }
    }

    /**
     * 更新当前位置文本和点击类型
     *
     * @param clickType 点击类型
     * @param curPoint  当前点击位置
     */
    private void updateCurPointTxt(String clickType, LatLng curPoint) {

        String txtPoint;
        if (txtCurPoint == null) {
            return;
        } else {
            txtPoint = String.format(clickType + "，当前经度：%.6f 当前纬度：%.6f", curPoint.getLongitude(), curPoint.getLatitude());
        }
        txtCurPoint.setText(txtPoint);
    }

    /**
     * 地图点击事件
     *
     * @param latLng 被点击的位置坐标
     */
    @SuppressLint("DefaultLocale")
    @Override
    public void onMapClick(@NonNull LatLng latLng) {

        updateCurPointTxt("单击地图", latLng);

        //给点击位置加个图标
        addMarker(latLng);
    }

    /**
     * 地图长按事件
     *
     * @param latLng 被点击的位置坐标
     */
    @Override
    public void onMapLongClick(@NonNull LatLng latLng) {

        updateCurPointTxt("长按地图", latLng);

        //给点击位置加个图标
        addMarker(latLng);

    }

    /**
     * 给地图添加标记
     *
     * @param latLng 位置
     */
    private void addMarker(@NonNull LatLng latLng) {

        if (marker == null) {
            marker = new MarkerLayerOptions.MarkerItem()
                    .icon(R.drawable.icon_marka + "")
                    .position(latLng);
        } else {
            marker.position(latLng);
        }

        if (curPosition == null) {
            MarkerLayerOptions Layer = new MarkerLayerOptions("locationMarkerLayer")
                    .iconAnchor(MarkerLayerOptions.ANCHOR_CENTER)//基准点
                    .iconPitchAlignment(MarkerLayerOptions.PITCH_ALIGNMENT_MAP);
            Layer.add(marker);
            curPosition = mineMap.addLayer(Layer);
        } else {
            curPosition.update();
        }
    }

    /**
     * 地图视角移动
     */
    @Override
    public void onCameraMove() {
        currentLatLng = mineMap.getCameraPosition().getTarget();

        if (lastLatLng != null && (lastLatLng.getLatitude() != currentLatLng.getLatitude()
                || lastLatLng.getLongitude() != currentLatLng.getLongitude())
                && !isRotate && !isShove)
            updateMapStateTxt("移动地图");
    }

    @Override
    public void onCameraMoveStarted(int reason) {
    }

    @Override
    public void onCameraIdle() {
    }

    @Override
    public void onScaleChanged(int i) {
        updateMapStateTxt("缩放地图");
    }

    @Override
    public void onRotateBegin() {
        isRotate = true;
        updateMapStateTxt("旋转地图");
    }

    @Override
    public void onRotate() {
        updateMapStateTxt("旋转地图");
    }

    @Override
    public void onRotateEnd() {
        updateMapStateTxt("旋转地图");
        isRotate = false;
    }

    @Override
    public void onShoveBegin() {
        isShove = true;
        updateMapStateTxt("俯仰地图");
    }

    @Override
    public void onShove() {
        updateMapStateTxt("俯仰地图");
    }

    @Override
    public void onShoveEnd() {
        updateMapStateTxt("俯仰地图");
        isShove = false;
    }

    //生命周期
    @Override
    protected void onStart() {
        super.onStart();
        if (mapView != null)
            mapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mapView != null)
            mapView.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null)
            mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null)
            mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null)
            mapView.onDestroy();
    }
}
